import { Request, Response } from 'express';
import { globalConfig } from '../../config/index';
import { regUserType, loginUserType, userInfoData } from './userType';
import { db } from '../../database/index';
import jwt from 'jsonwebtoken';
import bcryptjs from 'bcryptjs';

export const user = {
  // 用户注册
  regUser: (req: Request, res: Response) => {
    let userinfo: regUserType = req.body;
    const sqlRegisterSelect = `select * from ev_user where username=?`;
    db.query(sqlRegisterSelect, userinfo.username, (err, result) => {
      if (err) return res.send(err);
      if (result.length > 0) return res.send({
        status: 1,
        message: '当前用户已经存在！',
        data: null
      });

      const sqlRegister = `insert into ev_user set ?`;
      // 对用户的密码进行加密
      userinfo.password = bcryptjs.hashSync(userinfo.password, 10);
      db.query(
        sqlRegister,
        { username: userinfo.username, password: userinfo.password, role: userinfo.role },
        (err, result) => {
          if (err) return res.send(err);
          if (result.affectedRows !== 1) return res.send({
            status: 1,
            message: '注册用户失败，请重试！',
            data: null
          });

          return res.send({
            status: 0,
            message: '注册成功！',
            data: null
          });
        });
    });
  },

  // 用户登录 
  loginUser: (req: any, res: Response) => {
    const userinfo: loginUserType = req.body;
    const sqlLoginSelect = `select * from ev_user where username=?`;
    db.query(sqlLoginSelect, userinfo.username, (err, result) => {
      if (err) return res.send(err);
      if (result.length < 0) return res.send({
        status: 1,
        message: '用户不存在！',
        data: null
      });

      // 对加密的密码进行比对，正确就返回true，则登录成功，返回token
      const comparePwd = bcryptjs.compareSync(userinfo.password, result[0].password);
      if (comparePwd) {
        const user: userInfoData = { ...result[0], password: '', user_pic: '' };
        const strToken: string = jwt.sign(user, globalConfig.jwtSecretKey, { expiresIn: globalConfig.expiresIn });
        const userinfo: userInfoData = { ...result[0] };
        delete userinfo.password; // 去掉password返回结果给用户

        // 将用户信息和是否已登录存到session里，在修改密码和退出登录的时候去清空session
        req.session.user = user;
        req.session.isLogin = true;
        return res.send({
          status: 0,
          message: '登录成功！',
          data: {
            token: `Bearer ${strToken}`,
            userinfo: userinfo
          }
        })
      } else {
        res.send({
          status: 1,
          message: '密码错误！',
          data: null
        });
      }
    });
  },

  // 退出登录
  logoutUser: (req: any, res: Response) => {
    // 清除session里面的所有信息
    req.session.destroy();

    res.send({
      status: 0,
      message: '退出登录成功！',
      data: null
    });
  }
}